<template>
  <div class="page-container">
    <div class="page-header">
      <h2>实验模板管理</h2>
    </div>

    <!-- 主标签页 -->
    <el-tabs v-model="activeTab" class="main-tabs">
      <!-- 模板管理标签页 -->
      <el-tab-pane label="模板管理" name="templates">
        <div class="page-header-actions">
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            创建模板
          </el-button>
        </div>

        <!-- 搜索栏 -->
        <el-form :inline="true" class="search-form">
      <el-form-item label="模板名称">
        <el-input
          v-model="searchParams.name"
          placeholder="请输入模板名称"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table
      :data="templateStore.templates"
      v-loading="templateStore.loading"
      stripe
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="模板名称" min-width="200" />
      <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip />
      <el-table-column prop="tags" label="标签" width="200">
        <template #default="{ row }">
          <el-tag
            v-for="tag in row.tags"
            :key="tag"
            size="small"
            style="margin-right: 5px"
          >
            {{ tag }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="version" label="版本" width="80" />
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">详情</el-button>
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="templateStore.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handlePageChange"
      @current-change="handlePageChange"
    />

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      @close="handleDialogClose"
    >
      <el-form :model="form" label-width="100px" ref="formRef">
        <el-form-item label="模板名称" required>
          <el-input v-model="form.name" :disabled="isEdit" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板描述">
          <el-input v-model="form.description" type="textarea" rows="2" placeholder="请输入模板描述" />
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            placeholder="输入标签后回车添加"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="YAML内容" required>
          <YamlEditor v-model="form.yaml_content" :height="400" />
        </el-form-item>
        <el-form-item label="修改说明" v-if="isEdit">
          <el-input v-model="form.change_log" type="textarea" rows="2" placeholder="请输入修改说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="模板详情"
      width="70%"
    >
      <el-descriptions :column="2" border v-if="currentTemplate">
        <el-descriptions-item label="ID">{{ currentTemplate.id }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{ currentTemplate.name }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ currentTemplate.description }}</el-descriptions-item>
        <el-descriptions-item label="标签" :span="2">
          <el-tag v-for="tag in currentTemplate.tags" :key="tag" size="small" style="margin-right: 5px">
            {{ tag }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="版本">{{ currentTemplate.version }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(currentTemplate.created_at) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{ formatDate(currentTemplate.updated_at) }}</el-descriptions-item>
      </el-descriptions>

      <el-divider>YAML内容</el-divider>
      <YamlEditor v-model="currentTemplate.yaml_content" :height="400" :readonly="true" />

      <el-divider>版本历史</el-divider>
      <el-timeline v-if="currentTemplate.version_history && currentTemplate.version_history.length">
        <el-timeline-item
          v-for="version in currentTemplate.version_history"
          :key="version.version"
          :timestamp="formatDate(version.created_at)"
        >
          <h4>版本 {{ version.version }}</h4>
          <p>{{ version.change_log || '无修改说明' }}</p>
          <div class="version-actions">
            <el-button
              size="small"
              @click="handleCompareVersion(version.version)"
              v-if="version.version !== currentTemplate.version"
            >
              与当前版本对比
            </el-button>
            <el-button
              size="small"
              @click="handleRollback(currentTemplate.id, version.version)"
              v-if="version.version !== currentTemplate.version"
            >
              回滚到此版本
            </el-button>
          </div>
        </el-timeline-item>
      </el-timeline>
      <el-empty v-else description="暂无版本历史" />
    </el-dialog>

    <!-- 版本对比对话框 -->
    <el-dialog
      v-model="diffVisible"
      title="版本对比"
      width="80%"
      :close-on-click-modal="false"
    >
      <YamlDiff
        v-if="diffData.oldContent && diffData.newContent"
        :old-content="diffData.oldContent"
        :new-content="diffData.newContent"
        :old-version="diffData.oldVersion"
        :new-version="diffData.newVersion"
        style="height: 600px"
      />
      <el-empty v-else description="加载中..." />
    </el-dialog>
      </el-tab-pane>

      <!-- 配置预设标签页 -->
      <el-tab-pane label="配置预设" name="presets">
        <ConfigPresets />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTemplateStore } from '@/stores/template'
import YamlEditor from '@/components/YamlEditor/index.vue'
import YamlDiff from '@/components/YamlDiff/index.vue'
import ConfigPresets from './ConfigPresets.vue'
import dayjs from 'dayjs'

const router = useRouter()
const templateStore = useTemplateStore()

// 主标签页状态
const activeTab = ref('templates')

// 搜索参数
const searchParams = reactive({
  name: ''
})

// 分页参数
const pagination = reactive({
  page: 1,
  pageSize: 20
})

// 对话框状态
const dialogVisible = ref(false)
const detailVisible = ref(false)
const diffVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const currentTemplate = ref(null)
const formRef = ref(null)

// 版本对比数据
const diffData = reactive({
  oldContent: '',
  newContent: '',
  oldVersion: 1,
  newVersion: 2
})

// 表单数据
const form = reactive({
  name: '',
  description: '',
  yaml_content: '',
  tags: [],
  change_log: ''
})

const dialogTitle = computed(() => isEdit.value ? '编辑模板' : '创建模板')

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : ''
}

// 获取模板列表
const fetchList = async () => {
  await templateStore.fetchTemplates({
    page: pagination.page,
    page_size: pagination.pageSize,
    name: searchParams.name || undefined
  })
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchList()
}

// 重置
const handleReset = () => {
  searchParams.name = ''
  handleSearch()
}

// 分页改变
const handlePageChange = () => {
  fetchList()
}

// 创建模板
const handleCreate = () => {
  router.push('/experiment-templates/create')
}

// 编辑模板
const handleEdit = (row) => {
  router.push(`/experiment-templates/${row.id}/edit`)
}

// 查看详情
const handleView = (row) => {
  router.push(`/experiment-templates/${row.id}`)
}

// 删除模板
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个模板吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await templateStore.deleteTemplate(row.id)
    ElMessage.success('模板已删除')
    fetchList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!form.name || !form.yaml_content) {
    ElMessage.warning('请填写模板名称和YAML内容')
    return
  }

  submitting.value = true
  try {
    if (isEdit.value) {
      await templateStore.updateTemplate(form.id, {
        description: form.description,
        yaml_content: form.yaml_content,
        tags: form.tags,
        change_log: form.change_log
      })
      ElMessage.success('模板更新成功')
    } else {
      await templateStore.createTemplate({
        name: form.name,
        description: form.description,
        yaml_content: form.yaml_content,
        tags: form.tags,
        created_by: 'web_user'
      })
      ElMessage.success('模板创建成功')
    }
    dialogVisible.value = false
    fetchList()
  } catch (error) {
    console.error('操作失败:', error)
  } finally {
    submitting.value = false
  }
}

// 版本回滚
const handleRollback = async (id, version) => {
  try {
    await ElMessageBox.confirm(`确定要回滚到版本 ${version} 吗？`, '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await templateStore.rollbackVersion(id, version)
    ElMessage.success(`已回滚到版本 ${version}`)
    detailVisible.value = false
    fetchList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('回滚失败:', error)
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 版本对比
const handleCompareVersion = async (historyVersion) => {
  if (!currentTemplate.value) return

  try {
    // 使用现有的 getVersionDiff API
    const response = await templateStore.getVersionDiff(
      currentTemplate.value.id,
      {
        version1: historyVersion,
        version2: currentTemplate.value.version
      }
    )

    if (response && response.version1 && response.version2) {
      diffData.oldContent = response.version1.yaml_content
      diffData.newContent = response.version2.yaml_content
      diffData.oldVersion = response.version1.version
      diffData.newVersion = response.version2.version
      diffVisible.value = true
    } else {
      ElMessage.error('无法获取版本对比数据')
    }
  } catch (error) {
    console.error('获取版本对比失败:', error)
    ElMessage.error('获取版本对比失败')
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style lang="scss" scoped>
.main-tabs {
  :deep(.el-tabs__content) {
    padding: 20px 0;
  }
}

.page-header-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.search-form {
  margin-bottom: 20px;
}

:deep(.el-form-item) {
  .yaml-editor-wrapper {
    width: 100%;
  }
}

.version-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}
</style>
